﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VehicleScale.DataAccess;
using VehicleScale.Models;
using Library.Encrypt;

namespace VehicleScale.Forms.Files
{
    public partial class FrmUpdateStaffs : TemplateForm
    {
        #region Ctors
        /// <summary>
        /// Constructor for create new status
        /// </summary>
        public FrmUpdateStaffs()
        {
            InitializeComponent();

            Initialize();

            this.BackColor = Setting.BackColor;
            this.uiGroupBox1.BackColor = Setting.BackColor;
            this.Size = new Common().SizeUpdate;
        }

        #endregion

        #region Field Members

        private bool _isEdit = false;
        private bool _isBinding = false;
        private IEmployeeDataAccess _dataAccess = new EmployeeDataAccess();

        #endregion

        #region Property Members
        private EmployeeModel _employee = new EmployeeModel();
        public EmployeeModel Employee
        {
            get { return _employee; }
            set
            {
                if (_employee != value)
                {
                    _isEdit = true;
                    _employee = value;
                }
            }
        }

        private IList<EmployeeModel> _collection;
        public IList<EmployeeModel> Collection
        {
            set { _collection = value; }
        }
        #endregion

        #region Methods

        private void Initialize()
        {
            this.MaximizeBox = false;

            this.Load += new EventHandler(delegate
            {
                BindingControls();
                ValidatingControls();
            });
            this.btnSave.Click += new EventHandler(delegate { ClickButtonSave(); });
            this.btnClose.Click += new EventHandler(delegate { this.Close(); });
        }

        protected override void OnLoad(EventArgs e)
        {
            if (_isEdit)
                this.edtEmployeeID.Enabled = false;
            base.OnLoad(e);
        }

        private void ResetBindingControls()
        {
            this.edtEmployeeID.DataBindings.Clear();
            this.edtEmployeeName.DataBindings.Clear();
            this.edtTelephone.DataBindings.Clear();
            this.edtIdentification.DataBindings.Clear();
            this.edtAddress.DataBindings.Clear();
            this.edtDescription.DataBindings.Clear();
            this.edtUsername.DataBindings.Clear();
            this.chkActive.DataBindings.Clear();
            this._isBinding = false;
        }
        private void BindingControls()
        {
            if (!_isBinding)
            {
                this.edtEmployeeID.DataBindings.Add("Text", Employee, "EmployeeID");
                this.edtEmployeeName.DataBindings.Add("Text", Employee, "EmployeeName");
                this.edtTelephone.DataBindings.Add("Text", Employee, "Telephone");
                this.edtIdentification.DataBindings.Add("Text", Employee, "Identification");
                this.edtAddress.DataBindings.Add("Text", Employee, "Address");
                this.edtDescription.DataBindings.Add("Text", Employee, "Description");
                this.edtUsername.DataBindings.Add("Text", Employee, "Username");
                this.chkActive.DataBindings.Add("Checked", Employee, "Active");
                _isBinding = true;
            }
        }
        private void ValidatingControls()
        {
            string errorMessage;
            this.edtEmployeeName.Validating += new CancelEventHandler(delegate
            {
                errorMessage = String.IsNullOrEmpty(this.edtEmployeeName.Text) ?
                        ErrorException.Error("Họ tên nhân viên", errType.required) : String.Empty;
                errorProvider.SetError(this.edtEmployeeName, errorMessage);
            });

            this.edtAddress.Validating += new CancelEventHandler(delegate
            {
                errorMessage = String.IsNullOrEmpty(this.edtAddress.Text) ?
                        ErrorException.Error("Địa chỉ nhân viên", errType.required) : String.Empty;
                errorProvider.SetError(this.edtAddress, errorMessage);
            });

            this.edtIdentification.Validating += new CancelEventHandler(delegate
            {
                errorMessage = String.IsNullOrEmpty(this.edtIdentification.Text) ?
                    ErrorException.Error("CMND", errType.required, errType.onlynumeric) : String.Empty;
                errorProvider.SetError(this.edtIdentification, errorMessage);
            });

            this.edtUsername.Validating += new CancelEventHandler(delegate
            {
                errorMessage = String.IsNullOrEmpty(this.edtUsername.Text) ?
                        ErrorException.Error("Username", errType.required) : String.Empty;
                errorProvider.SetError(this.edtUsername, errorMessage);
            });

            this.edtIdentification.KeyPress += new KeyPressEventHandler(edtIdentification_KeyPress);
            this.edtTelephone.KeyPress += new KeyPressEventHandler(edtTelephone_KeyPress);
        }

        void edtTelephone_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) &&
                e.KeyChar != Convert.ToChar(Keys.Back) &&
                e.KeyChar != '-')
            {
                e.Handled = true;
            }
        }

        void edtIdentification_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && e.KeyChar != Convert.ToChar(Keys.Back))
            {
                e.Handled = true;
            }
        }

        #endregion

        #region Action Members

        /// <summary>
        /// Click button save
        /// </summary>
        private void ClickButtonSave()
        {
            bool invalidInput = false;

            foreach (Control ctrl in this.Controls)
            {
                if (errorProvider.GetError(ctrl) != String.Empty)
                {
                    invalidInput = true;
                    break;
                }
            }

            if (invalidInput)
            {
                Library.Tools.MsgBox.Show(Messages.ValidateInfoMessage, Messages.NoticeTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                this.errorProvider.Clear();

                _employee.ModifiedByID = Common.UserLogin.Username;
                _employee.ModifiedDate = DateTime.Now;

                if (!_isEdit)
                {
                    _employee.CreatedByID = Common.UserLogin.Username;
                    _employee.CreationDate = DateTime.Now;
                    _employee.Password = Encrypt.Encode("MD5", "1234");

                    if (_dataAccess.Add(_employee))
                    {
                        _collection.Add(_employee);
                        _employee = new EmployeeModel() { Active = true };
                        ResetBindingControls();
                        BindingControls();
                        try
                        {
                            LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Them Nhan vien : " + _employee.EmployeeName);

                        }
                        catch
                        {
                        }
                        this.edtEmployeeID.Focus();
                    }
                    else
                    {
                        Library.Tools.MsgBox.Show(String.Format(Messages.NewFailedMessage, "nhân viên"),
                            "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    if (_dataAccess.Edit(_employee))
                    {
                        try
                        {
                            LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Thay doi nhan vien : " + _employee.EmployeeName);
                        }
                        catch
                        {
                        }
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                        Library.Tools.MsgBox.Show(String.Format(Messages.ModifyFailedMessage, "nhân viên"),
                            "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        #endregion
    }
}
